package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.service.ArticleStaticPageService;
import com.heima.article.service.IApArticleContentService;
import com.heima.article.service.IApArticleService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.article.pojos.ApArticleContent;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileInputStream;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author 21236
 */
@Service
public class ArticleStaticPageServiceImpl implements ArticleStaticPageService {


    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IApArticleService articleService;

    @Override
    public void generateStaticPage(Long articleId) throws Exception {

        String fileName = "D://" + UUID.randomUUID().toString() + ".html";
        //1.从数据库查询文章详情
        ApArticleContent articleContent = contentService.getOne(new LambdaQueryWrapper<ApArticleContent>()
                .eq(ApArticleContent::getArticleId, articleId));
        //2.准备数据，输出为静态页面
        Template template = configuration.getTemplate("article.ftl");
        Map<String, Object> map = new HashMap<>();
        map.put("content", JSONArray.parseArray(articleContent.getContent()));
        template.process(map, new FileWriter(fileName));
        //3.将静态页面上传到minio
        String url = fileStorageService.uploadHtmlFile("", "detail.html", new FileInputStream(fileName));
        //4.更新静态文件地址
        ApArticle article = new ApArticle();
        article.setId(articleId);
        article.setStaticUrl(url);
        articleService.updateById(article);
    }

    @Override
    public void removeStaticPage(Long articleId) {
        //1.从数据库查询文章信息
        ApArticle article = articleService.getById(articleId);
        //删除minio静态页面
        fileStorageService.delete(article.getStaticUrl());
        //更新文章信息
        article.setStaticUrl(null);
        articleService.updateById(article);
    }
}
